package com.example.demo.controller;

import com.example.demo.common.Cnst;
import com.example.demo.common.ResponseCode;
import com.example.demo.common.ServerResponse;
import com.example.demo.entity.User;

import com.example.demo.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@RestController
@RequestMapping("/user")
public class UserController{
    @Autowired
    private IUserService iUserService;

    @PostMapping("/login")
    public ServerResponse<User> login(String username, String password, String check, HttpSession session){
        System.out.println(username+"+"+password+"+"+check);
        ServerResponse serverResponse=iUserService.login(username,password,check);
        if(serverResponse.isSucc())session.setAttribute(Cnst.CURRENT_USER,serverResponse.getData());
        return serverResponse;
    }
    @PostMapping("/register")
    public ServerResponse register(User user){
        ServerResponse serverResponse=iUserService.register(user);
        return serverResponse;
    }
    @GetMapping("/findOne")
    public ServerResponse findOne(HttpSession session){
        //获取session中的用户
        User loginUser=(User) session.getAttribute(Cnst.CURRENT_USER);

        if(loginUser==null){
            return ServerResponse.failWithCodeMsg(ResponseCode.NEED_LOGIN.getCode(),"用户未登录！请");
        }else {
            return ServerResponse.succWithMsgData("sccess",loginUser);
        }
    }
    @GetMapping("/loginOut")
    public void loginOut(HttpSession session, HttpServletResponse response) throws IOException {
        //移除session中的登录的用户
        session.removeAttribute(Cnst.CURRENT_USER);
        //throws IOException
        response.sendRedirect("/index.html");
    }
}
